<?php


namespace api\modules\v1\controllers\rbac;

use Yii;
use yii\web\HttpException;
use api\controllers\OnAuthController;
use common\helpers\CommonHelper;
use common\models\member\Attr;
use common\models\member\Member;
use common\models\base\Profession;
use services\member\MemberService;

class UserController extends OnAuthController
{
    public $modelClass = [];

    /**
     * @api get /v1/rbac/user/index 人员列表
     * @apiName index
     * @apiGroup user
     *
     * @apiParam {String} keyword                               关键词
     * @apiParam {Number} profession_id                         岗位ID
     * @apiParam {Number} department_id                         部门ID
     * @apiParam {Number} clinic_id                             诊室ID
     * @apiParam {Number} role_id                               角色ID
     * @apiParam {Number} status                                状态
     * @apiParam {Number} page                                  页码
     * @apiParam {Number} pageSize                              每页显示数
     *
     * @apiSuccess {Object} data                                返回数据
     * @apiSuccess {Number} data.page                           当前页码
     * @apiSuccess {Number} data.pageSize                       每页显示数
     * @apiSuccess {Number} data.total                          总数
     * @apiSuccess {Array}  data.list                           列表
     * @apiSuccess {Array}  data.condition                      筛选条件
     * @apiSuccess {Array}  data.condition.clinic_list          诊室列表
     * @apiSuccess {Number} data.condition.clinic_list.id       ID
     * @apiSuccess {String} data.condition.clinic_list.name     名称
     * @apiSuccess {Array}  data.condition.department_list      部门列表【同上】
     * @apiSuccess {Array}  data.condition.profession_list      岗位列表【同上】
     * @apiSuccess {Array}  data.condition.role_list            角色列表【同上】
     *
     */
    public function actionIndexUser()
    {
        $params = Yii::$app->request->get();
        $params['department_leader_id'] = intval($params['department_leader_id'] ?? 0);
        $params['profession_id'] = intval($params['profession_id'] ?? 0);
        $params['department_id'] = intval($params['department_id'] ?? 0);
        $params['clinic_id'] = intval($params['clinic_id'] ?? 0);
        $params['role_id'] = intval($params['role_id'] ?? 0);
        $params['projectId'] = $this->projectId;
        $params['keyword'] = trim($params['keyword'] ?? '');
        $params['status'] = $params['status'] ?? null;
        $params['limit'] = intval($params['pageSize'] ?? $this->limit);
        $params['page'] = intval($params['page'] ?? 1);

        // 判断是不是超管和项目管理员
        $member = Yii::$app->user->identity->member;
        $attr = Attr::find()
            ->where([
                'member_id' => $member['id'],
                'project_id' => $this->projectId
            ])
            ->asArray()
            ->one();

        $projectManager = $attr['is_department_leader'] ?? 0;

        // 不是项目管理员,且不是超管,不能看
        if ($member['is_super'] == Member::IS_SUPER_NO && ($projectManager == Attr::IS_DEPARTMENT_LEADER_NO || $projectManager == Attr::IS_DEPARTMENT_LEADER_YES)) {
            return ['list' => [], 'total' => 0, 'pageSize' => $params['limit'], 'page' => $params['page']];
        }

        $data = MemberService::getList($params);

        // 筛选条件
        $cdata = [
            'get_clinic' => 1,
            'get_department' => 1,
            'get_profession' => 1,
            'get_role' => 1,
        ];
        $data['condition'] = Yii::$app->services->patientUser->getConditionList($cdata, $this->projectId);

        return $data;
    }

    public function actionCreateUser()
    {
        $params = Yii::$app->request->post();
        $name = trim($params['name'] ?? '');
        $mobile = trim($params['mobile'] ?? '');
        $professionId = intval($params['profession_id'] ?? 0);
        $professionModel = Profession::findOne($professionId);
        $professionName = $professionModel ? $professionModel->name : "";
        $departmentId = intval($params['department_id'] ?? 0);
        //   $is_department_leader = intval($params['is_department_leader'] ?? Attr::IS_DEPARTMENT_LEADER_NO);
        $password = trim($params['password'] ?? '');
        $password_re = trim($params['password_re'] ?? '');
        if ($password != $password_re) {
            throw new HttpException(422, '两次密码不一致,请确认密码');
        }
        $projectArray[] = $this->projectId;
        $role_id = $params['role_id'];
        $room_id = $params['room_id'] ?? "";
        $user_name = trim($params['user_name'] ?? '');
        $status = intval($params['status'] ?? Member::STATUS_INVALID);
        $gender = intval($params['gender'] ?? Member::GENDER_UNKNOW);
        $password = $password ?: '123456';
        $clinic_id = intval($params['clinic_id'] ?? 0); // 诊室id

        if (!$name || !$mobile || !$professionId || !$role_id) {
            throw new HttpException(422, '新增失败，基本信息不能为空！');
        }

        // 判断手机号是否唯一
        $memberExists = Member::find()->where(['mobile' => $mobile])->andWhere(['!=', 'status', Member::STATUS_DELETE])->exists();
        if ($memberExists) {
            throw new HttpException(422, '新增失败，手机号已存在！');
        }

        if ($professionId == Profession::ID_MEDICAL || $professionId == Profession::ID_CUSTOMER) {
            /*if (!$clinic_id) {
                throw new HttpException(422, '请选择诊室');
            }*/
        } else {
            $clinic_id = 0;
        }

        try {
            $data = [
                'name' => $name,
                'user_name' => $user_name,
                'mobile' => $mobile,
                'professionId' => $professionId,
                'department_id' => $departmentId,
                'project_id' => $projectArray,
                'role_id' => array_filter(explode(',', $role_id)),
                'room_id' => array_filter(explode(',', $room_id)),
                'status' => $status,
                'gender' => $gender,
                'professionName' => $professionName,
                'password_hash' => Yii::$app->security->generatePasswordHash($password),
                'auth_key' => Yii::$app->security->generateRandomString(),
//                'is_department_leader' => $is_department_leader,
                'password' => $password,
                'clinic_id' => $clinic_id,
            ];
            $res = MemberService::createMember($data);
        } catch (\Exception $exception) {
            throw new HttpException(500, $exception->getMessage());
        }

        return $res;
    }

    public function actionUpdateUser()
    {
        $params = Yii::$app->request->post();
        $id = intval($params['id'] ?? 0);
        $name = trim($params['name'] ?? '');
        $user_name = trim($params['user_name'] ?? '');
        $mobile = trim($params['mobile'] ?? '');
        $password = trim($params['password'] ?? '');
        $password_re = trim($params['password_re'] ?? '');

        if ($password != $password_re) {
            throw new HttpException(422, '两次密码不一致,请确认密码');
        }
        $projectArray = [$this->projectId];
        $professionId = trim($params['profession_id'] ?? 0);
        $departmentId = intval($params['department_id'] ?? 0);
        $gender = intval($params['gender'] ?? Member::GENDER_UNKNOW);
        $clinic_id = intval($params['clinic_id'] ?? 0); // 诊室id
        $professionModel = Profession::findOne($professionId);
        $professionName = $professionModel ? $professionModel->name : "";
        $roleIds = trim($params['role_id'] ?? '');
        $roomIds = trim($params['room_id'] ?? '');
        $status = intval($params['status'] ?? Member::STATUS_INVALID);
        $is_department_leader = intval($params['is_department_leader'] ?? Attr::IS_DEPARTMENT_LEADER_NO);
        if (!$name || !$mobile || !$roleIds) {
            throw new HttpException(422, '修改失败，姓名或手机号不能为空！');
        }

        // 判断id对应的信息是否存在
        $memberExists = Member::find()->where(['id' => $id])->exists();

        if (!$memberExists) {
            throw new HttpException(422, '编辑失败，对应的id不存在！');
        }

        // 判断手机号是否已存在
        $mobileExists = Member::find()->where(['mobile' => $mobile])->andWhere(['!=', 'id', $id])->andWhere(['!=', 'status', Member::STATUS_DELETE])->exists();
        if ($mobileExists) {
            throw new HttpException(422, '编辑失败，该手机号已存在！');
        }

        if ($professionId == Profession::ID_MEDICAL || $professionId == Profession::ID_CUSTOMER) {
            /*if (!$clinic_id) {
                throw new HttpException(422, '请选择诊室');
            }*/
        } else {
            $clinic_id = 0;
        }

        $data = [
            'name' => $name,
            'user_name' => $user_name,
            'gender' => $gender,
            'mobile' => $mobile,
            'project_id' => $projectArray,
            'department_id' => $departmentId,
            'password_hash' => $password ? Yii::$app->security->generatePasswordHash($password) : '',
            'professionId' => $professionId,
            'professionName' => $professionName,
            'roleIdData' => array_filter(explode(',', $roleIds)),
            'roomIdData' => array_filter(explode(',', $roomIds)),
            'status' => $status,
            'clinic_id' => $clinic_id,
            'is_department_leader' => $is_department_leader,
            'password' => $password,
        ];

        try {
            $res = MemberService::updateUser($data, $id);
        } catch (\Exception $exception) {
            return CommonHelper::api(422, $exception->getMessage());
        }

        return $res;
    }


    /**
     * @param int $id 员工id
     *
     * @apiSuccess {Number} code    状态码，200：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} data    返回数据
     *
     * @return array
     * @api get /v1/rabc/view
     * @apiGroup member
     * @apiName 员工详情
     * @apiVersion 1.0.0
     *
     * @apiDescription 员工详情
     */
    public function actionViewUser()
    {
        $params = Yii::$app->request->get();
        $project_id = $this->projectId;
        $params['project_id'] = $project_id;

        $res = MemberService::viewUser($params);
        return $res;
    }


}
